package com.iexbuy.ihg.ui.fragment;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.adapter.ShopItemListAdapter;
import com.iexbuy.ihg.adapter.ShopsAdapter;
import com.iexbuy.ihg.adapter.YunGuoItemListAdapter;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.common.ExtraKeyConstant;
import com.iexbuy.ihg.entity.AdObject;
import com.iexbuy.ihg.entity.BusinessType;
import com.iexbuy.ihg.entity.LuckUserListObject;
import com.iexbuy.ihg.entity.LuckUserListObjectResponse;
import com.iexbuy.ihg.entity.Shop;
import com.iexbuy.ihg.entity.ShopItemListObjectResponse;
import com.iexbuy.ihg.entity.YunItemListObject;
import com.iexbuy.ihg.entity.YunItemListObjectResponse;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.ToastUtils;
import com.iexbuy.ihg.utils.UnitUtils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

public class HomeYunGuoFragment extends BaseFragment {
	
	private static HomeYunGuoFragment homeFragmentInstent;

	@ViewInject(R.id.msgListLayout)
	private PullToRefreshLayout msgListRefreshLayout;
	@ViewInject(R.id.titleLayout)
	private RelativeLayout titleLayout;
	@ViewInject(R.id.listView)
	private ListView listView;

	private LinearLayout listHeaderView;
	@ViewInject(R.id.adItemList)
	private RelativeLayout adItemList;
	@ViewInject(R.id.zeroGuoLastThreeLuckly)
	private LinearLayout zeroGuoLastThreeLuckly;
//	@ViewInject(R.id.zeroGuoLastFour1)
//	private LinearLayout zeroGuoLastFour1;
//	@ViewInject(R.id.zeroGuoLastFour2)
//	private LinearLayout zeroGuoLastFour2;
	@ViewInject(R.id.zeroGuoLastFourGrid)
	private GridView zeroGuoLastFourGrid;
	@ViewInject(R.id.ad0GList)
	private RelativeLayout ad0GList;

	private List<AdObject> adObjects = new ArrayList<AdObject>();
	private List<View> adItemViews = new ArrayList<View>();

	private List<Shop> shops = new ArrayList<Shop>();
	private int pageNo = 0;
	private YunGuoItemListAdapter yunGuoItemListAdapter;

	//云购
	private List<YunItemListObject> yunItemListObjects = new ArrayList<YunItemListObject>();
	private List<YunItemListObject> yunItemListObjectLast4 = new ArrayList<YunItemListObject>();

	//热门分类
	private List<BusinessType> businessTypes = new ArrayList<BusinessType>();
	private List<View> businessTypePageViews = new ArrayList<View>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_yunguo, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		mBaseActivity.setTitle(getResources().getString(R.string.title_yun_guo));
		mBaseActivity.setLeftButtonVisibility(View.GONE);
		mBaseActivity.setSlideRightBackEnable(false);

		listHeaderView = (LinearLayout) mBaseActivity.getLayoutInflater().from(mBaseActivity).inflate(R.layout.fragment_yunguo_header, null);
		ViewUtils.inject(this, listHeaderView);

		listView.addHeaderView(listHeaderView);

		msgListRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				refreshDate();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				loadMore();
			}
		});
		msgListRefreshLayout.autoRefresh();
	}

	//刷新整个页面数据
	private void refreshDate() {
		pageNo = 0;
		initListDate();
	}

	/**
	 * 刷新列表数据
	 */
	private void initListDate() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("pageNo", String.valueOf(pageNo));
		paramMap.put("pageSize", String.valueOf(ExtraKeyConstant.COMMON_PAGE_SIZE));
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_READY_OPEN_ITEMS, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.REFRESHING);
					}

					@Override
					public void onCancelled() {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.DONE);
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
						YunItemListObjectResponse rsp = JsonUtils.parseJsonStrToObject(responseInfo.result, YunItemListObjectResponse.class);
						if (pageNo == 0) {
							yunItemListObjects.clear();
						}
						yunItemListObjects.addAll(rsp.getBody());
						initListView();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						msgListRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}

	private void loadMore() {
		pageNo ++;
		initListDate();
	}

	private void initListView() {
		initLastFormReadyItemView();
		if (yunGuoItemListAdapter == null) {
			yunGuoItemListAdapter = new YunGuoItemListAdapter(mBaseActivity, yunItemListObjects);
			listView.setAdapter(yunGuoItemListAdapter);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
					YunGuoItemDetailFragment.setYunItemListObject(yunItemListObjects.get(i-1));

					CommUtil.openSingleFragmentActivity(mBaseActivity, YunGuoItemDetailFragment.class);
				}
			});
			//加载列表头部
			CommUtil.initAdListData(mBaseActivity, "5", adItemList);
			initLash3LucklyData();
			CommUtil.initAdListData(mBaseActivity, "6", ad0GList);
		}
		yunGuoItemListAdapter.notifyDataSetChanged();

	}

	/**
	 * 最新开奖
	 */
	private void initLastFormReadyItemView() {
		for (int i = 0; i < 4; i ++) {
			yunItemListObjectLast4.add(yunItemListObjects.get(i));
			yunItemListObjects.remove(i);
		}
		zeroGuoLastFourGrid.setAdapter(new BaseAdapter() {
			@Override
			public int getCount() {
				return 4;
			}
			@Override
			public Object getItem(int i) {
				return yunItemListObjectLast4.get(i);
			}
			@Override
			public long getItemId(int i) {
				return -1;
			}
			@Override
			public View getView(int i, View view, ViewGroup viewGroup) {
				if (view == null) {
					view = mBaseActivity.getLayoutInflater().from(mBaseActivity).inflate(R.layout.fragment_yunguo_last_4_item, null);
				}
				YunItemListObject vo = yunItemListObjectLast4.get(i);
				view.setTag(vo);

				((TextView) view.findViewById(R.id.yungouName)).setText(vo.getItemName());
				((TextView) view.findViewById(R.id.attendanceNo)).setText(vo.getAttandanceNumber());
				((TextView) view.findViewById(R.id.totalRequireNo)).setText(vo.getRequiredTotalNumber());
				((TextView) view.findViewById(R.id.balenceNo)).setText(String.valueOf(Integer.valueOf(vo.getRequiredTotalNumber()) - Integer.valueOf(vo.getAttandanceNumber())));
				((TextView) view.findViewById(R.id.balenceNoText)).setText("剩余" + String.valueOf(Integer.valueOf(vo.getRequiredTotalNumber()) - Integer.valueOf(vo.getAttandanceNumber())) + "人");
				((ProgressBar) view.findViewById(R.id.yunProgress)).setProgress(new BigDecimal(vo.getAttandanceNumber()).divide(new BigDecimal(vo.getRequiredTotalNumber()), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).intValue());
				App.bitmapUtils.display((ImageView) view.findViewById(R.id.yungouImg), vo.getThumbnailUrl());

				return view;
			}
		});
		zeroGuoLastFourGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				YunGuoItemDetailFragment.setYunItemListObject((YunItemListObject)view.getTag());//列表有头部
				CommUtil.openSingleFragmentActivity(mBaseActivity, YunGuoItemDetailFragment.class);
			}
		});
	}

	/**
	 * 最新中奖
	 */
	private void  initLash3LucklyData() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("pageNo", String.valueOf(pageNo));
		paramMap.put("pageSize", "3");
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_LASH_LUCK_USERS, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LuckUserListObjectResponse rsp = JsonUtils.parseJsonStrToObject(responseInfo.result, LuckUserListObjectResponse.class);
						initLast3LucklyUsersView(rsp.getBody());
					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
	}

	private void initLast3LucklyUsersView(List<LuckUserListObject> luckUserListObjects) {
		zeroGuoLastThreeLuckly.removeAllViews();
		TextView userView = null;
		LinearLayout llView = null;
		ImageView iv=null;
		for (LuckUserListObject lu : luckUserListObjects) {
			llView = new LinearLayout(mBaseActivity);
			llView.setOrientation(LinearLayout.HORIZONTAL);
			llView.setGravity(Gravity.CENTER);
			iv=new ImageView(mBaseActivity);
			iv.setImageResource(R.drawable.arrow_right);
			iv.setAlpha(0.3f);
			LinearLayout.LayoutParams lpiv = new LinearLayout.LayoutParams(UnitUtils.dip2px(mBaseActivity,8), UnitUtils.dip2px(mBaseActivity,10));
			iv.setLayoutParams(lpiv);
			userView = new TextView(mBaseActivity);
			userView.setSingleLine(true);
			userView.setEllipsize(TextUtils.TruncateAt.END);

			userView.setText("恭喜" + lu.getUserName() + "获得了(第" + lu.getPeriod() + "期)" + lu.getItemName());
			userView.setTextColor(getResources().getColor(R.color.list_text_detail));
			userView.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_white));
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT,1);
			lp.setMargins(0, UnitUtils.dip2px(mBaseActivity, 10), UnitUtils.dip2px(mBaseActivity, 10), UnitUtils.dip2px(mBaseActivity, 10));
			userView.setLayoutParams(lp);
			llView.setTag(lu);

			llView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					LuckUserListObject luckUser = (LuckUserListObject) view.getTag();
					YunGuoItemDetailFragment.setYunItemListObject(new YunItemListObject(luckUser.getItemId()));
					CommUtil.openSingleFragmentActivity(mBaseActivity, YunGuoItemDetailFragment.class);
				}
			});
			llView.addView(userView);
			llView.addView(iv);
			zeroGuoLastThreeLuckly.addView(llView);
		}
	}



	/**
	 * @return the homeFragmentInstent
	 */
	public static HomeYunGuoFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
